import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  message, 
  Tag, 
  Space,
  Card,
  Typography
} from 'antd';
import { 
  PlayCircleOutlined, 
  StopOutlined,
  LinkOutlined
} from '@ant-design/icons';
import { getInstances, stopInstance, startInstance } from '../../services/api';

const { Title } = Typography;

const InstanceList = () => {
  const [instances, setInstances] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchInstances = async () => {
    try {
      setLoading(true);
      const response = await getInstances();
      setInstances(response.data.instances);
    } catch (error) {
      message.error('Failed to fetch instances: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstances();
  }, []);

  const handleStop = async (id) => {
    try {
      const response = await stopInstance(id);
      message.success(response.data.message);
      fetchInstances();
    } catch (error) {
      message.error('Failed to stop instance: ' + error.message);
    }
  };

  const handleStart = async (id) => {
    try {
      const response = await startInstance(id);
      message.success(response.data.message);
      fetchInstances();
    } catch (error) {
      message.error('Failed to start instance: ' + error.message);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'Running':
        return 'green';
      case 'Stopped':
        return 'red';
      default:
        return 'default';
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'Function ID',
      dataIndex: 'functionId',
      key: 'functionId',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status) => <Tag color={getStatusColor(status)}>{status}</Tag>,
    },
    {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      render: (url) => (
        <a href={url} target="_blank" rel="noopener noreferrer">
          <LinkOutlined /> {url}
        </a>
      ),
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_, record) => (
        <Space size="middle">
          {record.status === 'Running' ? (
            <Button 
              icon={<StopOutlined />} 
              onClick={() => handleStop(record.id)}
              danger
            >
              Stop
            </Button>
          ) : (
            <Button 
              icon={<PlayCircleOutlined />} 
              onClick={() => handleStart(record.id)}
              type="primary"
            >
              Start
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Title level={3}>Instances</Title>
        <Button onClick={fetchInstances}>Refresh</Button>
      </div>
      <Table
        dataSource={instances}
        columns={columns}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
    </Card>
  );
};

export default InstanceList;